import java.io.*;
import java.net.SocketException;
import java.util.concurrent.Semaphore;
//PeerProcess is the real main for each process
public class PeerProcess {
public static void main(String args[])
{
	long sleeptime;
	int counter=0;
	if(args.length!=4)
	{
		return;
	}

	SystemConfig.setPid(args[0]);
	SystemConfig.setAddr(args[1]);
//multicast address are hard coded because lack of specification 
	SystemConfig.setGroupAddr(args[2]);
	SystemConfig.setGroupPort(Integer.parseInt(args[3]));
	
	Semaphore token=new Semaphore(1);
	try {
		TokenPassing tp=new TokenPassing(token);
		
		try {
			tp.initial();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Utils.writeLog("first Peer, form a cycle of size 1");
		}//initialization phase
		
		tp.setActiveFlag(true);
		tp.start();	
		
		tp.setActiveFlag(true);
		
		Multicast mc=new Multicast(tp);
		mc.start();
		while(true)//main loop
		{
					token.acquire();//requrie token
					counter++;
					sleeptime=Utils.Random(500, 1000);
					Thread.sleep(sleeptime);
					Utils.writeLog(counter);
					token.release();
					sleeptime=Utils.Random(3000, 5000);
		}
	}  catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}
